/**
 * Created by sunny.w <iwisunny@gmail.com> on 15-4-25.
 */

wxi.namespace('wxi.util', {
    //check error images, replace with default placeholder
    checkImageError: function(option){
        option = wxi.extend({
            placeholder: '/img/placeholder.jpg'
        }, option);

        $('img').error(function(){
            $(this).attr('src', option.placeholder);
        });
    },
    //jquery.gritter wrapper
    tipMsg: function(title, msg, delay, cb){
        var _run = function(){
            //$.gritter wrapper
            $.gritter.add({
                'title': title || '操作提示',
                'text': msg || '提示信息...',
                'time': delay || 1500
            });

            if(cb && typeof cb == 'function'){
                setTimeout(function(){
                    cb.apply(this, arguments);
                }, parseInt(delay));
            }
        };

        //pre check if $.gritter is loaded
        if($.gritter === undefined){
            //not load jq.gritter, try load it async
            var loaded = false;
            wxi.require('jquery.gritter.min.js', function(){
                try{
                    if($.gritter){
                        loaded = true;
                        _run();
                    }
                    else{
                        throw new Error('jq.gritter not loaded');
                    }
                }
                catch(e){
                    alert(e.message);
                }

            });

        }
        else{
            _run();
        }

    },

    //area content lazy loader
    loadContent: function(area, fx, timeout){
        var icon = '/img/loading.gif',
            html =  '<div style="margin-left:40%;" id="loading-area">' +
                '<img src="'+ icon +  '" width="100px" height="100px"/></div>';

        if(typeof area =='string'){
            area=$(wxi.string.trim(area, ['#','.'],1));
        }
        else{
            area=$(area);
        }

        $(area).html(html);

        var remove_icon=function(){
            $(area).find('#loading-area').remove();
        };

        if( timeout === undefined){
            fx(remove_icon);
        }
        else{
            setTimeout(fx, parseInt(timeout));
        }

    },
    //util to get cookie value by name
    getCookie: function(cname){
        var cookie = document.cookie.split(";");
        if(cname === undefined) return cookie.join("\n");

        for(var i= 0, len = cookie.length; i < len; i++){
            var part = cookie[i].split('=');
            if($.trim.call(part[0]) === cname){
                return decodeURIComponent(part[1]);
            }
        }
    },
    setCookie: function(cname, cval, expire, domain, path){
        var domain = domain || 'yourdomain.com',
            path = path || '/',
        //cookie string part
            cs = cname + '=' + encodeURIComponent(cval),
            tm = new Date,
            now = +tm;

        // use expire as seconds
        if(expire > 0){
            tm.setTime(now + parseInt(expire)*1000 );
        }
        else{
            tm.setTime(now -1 );
        }
        expire = tm.toGMTString();
        cs += "; expires=" + expire;
        cs += '; domain='+domain;
        cs += '; path='+path;
        document.cookie = cs;
    },

    getCache: function(key){
        if(key===undefined){
            return wxi.util._cache|| {};
        }
        return wxi.util._cache ? wxi.util._cache[key] : undefined;
    },
    setCache: function(key, data){
        var c=wxi.util._cache || {};
        c[key]=data;

        wxi.util._cache=c;
        return data;

    },
    clearCache: function(){
        wxi.util._cache={};
        return true;
    }


});

//namespace: string
wxi.namespace('wxi.string', {
    //uppercase first char
    ucfirst: function(str){
        return (str[0]).toUpperCase() + str.substr(1);
    },

    //query string to json
    qs2obj: function(qs, filter){
        var obj = {};

        filter=filter || '';

        if(typeof qs == 'string'){
            var parts = qs.split('&');
            wxi.map(parts, function(item){
                var _item = item.split('=');
                obj[_item[0]] = _item[1];
            });
        }

        //post filter
        if(filter && typeof filter == 'function'){
            return filter.apply(null, [obj, ]);
        }

        return obj;
    },

    trim: function(str, blacklist, trim_type){
        //TODO：改为静态属性
        var TRIM_LEFT= 1,
            TRIM_RIGHT= 2,
            TRIM_BOTH= 3;   //去除两端

        blacklist=blacklist || '';
        trim_type=trim_type || TRIM_BOTH;

        var trim_left=function(str,blacklist){
            if(wxi.isArray(blacklist)){
                exp=new RegExp('^'+ blacklist.join('|'));
            }
            else{
                exp=new RegExp('^'+blacklist);
            }
            return str.replace(exp,'');
        };
        var trim_right=function(str, blacklist){
            if(wxi.isArray(blacklist)){
                exp=new RegExp( blacklist.join('|')+'$');
            }
            else{
                exp=new RegExp(blacklist+'$');
            }
            return str.replace(exp,'');
        };

        var exp=null;

        if(trim_type == TRIM_LEFT){
            return trim_left(str, blacklist);
        }
        else if(trim_type == TRIM_RIGHT){
            return trim_right(str, blacklist);
        }
        else if(trim_type == TRIM_BOTH){
            //assume trim both
            var s=trim_left(str,blacklist);
            return trim_right(s, blacklist);
        }

    },

    htmlEncode: function(raw_str){
        if(!raw_str) return '';
        return raw_str.replace(/&lt;/g, '<').replace(/&gt;/g,'>');
    }

});

//util for shop_admin_bundle
wxi.namespace('wxi.shopBundle',{
    /**
     * city_data must be json
     * @param city_data
     */
    getCityList: function(callback){
        //TODO: ajax url 暂时写死
        var ajax_fetch_city='/api/get_city_data';

        //ajax fetch city data
        $.get(ajax_fetch_city, function (city_data) {

            if(!city_data){
                throw new Error('get city data failed');
            }

            //cache city data to wxi cache object
            if(wxi.isObject(city_data)){
                wxi.util.setCache('cityData', city_data);
            }
            else if(wxi.isArray(city_data)){
                //解析 city-origin.json
                var city_map=[];
                var add_city_item=function(city_list){
                    wxi.map(city_list, function(city){
                        if(city.children.length>0){
                            add_city_item(city.children);
                        }
                        else{
                            if(city.name){
                                city_map.push({
                                    name:city.name,
                                    id:city.id,
                                    district:city.district
                                });
                            }
                        }

                    });

                    return city_map;
                };

                wxi.util.setCache('cityData', add_city_item(city_data) );
            }

            //add callback
            if(callback && typeof callback =='function'){
                callback.call(null);
            }

        });
    },

    /**
     *@return 根据表单name字段生成的 entity 对象
     */
    preCheckForm: function(form_wrap, strip_str){
        var form_data=form_wrap.serialize();

        return (function(){
            return wxi.string.qs2obj(form_data, function(obj){
                var ret={};
                if(wxi.isObject(obj)){
                    for(var p in obj){

                        var data=decodeURIComponent(obj[p]);
                        var filter_p=decodeURIComponent(p);

                        var filtered_key= filter_p.replace(strip_str,'');
                        filtered_key=filtered_key.substring(1, filtered_key.length-1);

                        ret[filtered_key]=data;
                    }

                    if('_token' in ret){
                        delete ret._token;
                    }
                }

                return ret;

            });

        })();

    },

    fillSelect: function(select_obj, fill_data, with_val_id){
        var cont='<option value="0">--请选择--</option>';

        with_val_id=with_val_id || false;

        if(wxi.isArray(fill_data)){
            wxi.map(fill_data, function(row, idx){
                //iteration , row is city object
                //cont += '<option value="'+row.id+'">'+row.name+'</option>'+"\n";
                if(with_val_id){
                    cont += '<option value="'+row.id+'">'+row.name+'</option>'+"\n";
                }
                else{
                    cont += '<option value="'+row+'">'+row+'</option>'+"\n";
                }
            });
        }
        else if(wxi.isObject(fill_data)){
            for(var ct_name in fill_data){
                cont += '<option value="'+ct_name+'">'+ct_name+'</option>'+"\n";
            }
        }

        $(select_obj).html(cont);
    },

    //加载富文本编辑器
    loadEditor: function(editor_id, cb){
        var prefix='/plugins/ueditor/';
        var js_files=[
            'ueditor.config.js',
            'ueditor.all.min.js',
            'lang/zh-cn/zh-cn.js'
        ];

        //override ueditor path
        window.UEDITOR_HOME_URL=prefix;
        var ueditor_conf={
            toolbars: [
                [
                    'source', '|','undo', 'redo', '|','autotypeset','pasteplain', 'formatmatch','removeformat',
                    '|','justifyleft','justifyright','justifycenter','justifyjustify',
                    '|','forecolor', 'backcolor', 'bold', 'underline', 'strikethrough','horizontal', 'link','unlink',
                    'insertorderedlist', 'insertunorderedlist','rowspacingtop','rowspacingbottom',
                    '|','inserttable','deletetable',
                    '|','insertrow','insertcol','mergeright','mergedown',
                    '|','insertparagraphbeforetable',
                    '|','splittorows', 'splittocols','splittocells', 'deletecaption',
                    '|','inserttitle','mergecells','edittable','edittd',
                    '|','simpleupload', 'insertimage',
                    '|','emotion',
                    '|','searchreplace','fullscreen','imagenone','imageleft','imageright','imagecenter',
                    'lineheight','edittip '
                ]
            ],

            enterTag:'',
            //initialFrameHeight:300,
            allowDivTransToP: false,

            //服务端配置
            serverUrl: prefix + 'php/controller.php'
        };

        wxi.require(js_files,function(){

            UE.getEditor(editor_id, ueditor_conf).ready(function(){
                var ue=UE.getEditor(editor_id);

                cb.apply(null, [ue]);

                /////////////////////////////debug info
                console.info('editor loaded');

                //恢复wxi.require的包含路径到系统默认值
                wxi.setConfig({
                    jsBaseUrl:'/js/',
                    cssBaseUrl: '/css/'
                });

            });


        },{jsBaseUrl:prefix} );

    },

    //封装loadContent, loadEditor, ajax lazy load ueditor
    registerEditor: function(wrap, editor_id, callback){
        //cb 为wxi.util.loadContent的闭包函数，用于回调完成之后移除loading-icon
        wxi.util.loadContent(wrap, function(cb){

            //loadEditor完成时调用cb,属于partial valuate,然后再去执行附加匿名函数
            wxi.shopBundle.loadEditor(editor_id, function(ue){
                //ue 为闭包变量
                cb.call();

                typeof callback == 'function' && callback.apply(null, [ue]);

            });
        });
    }

});